import axios from 'axios';
import { ElMessage } from 'element-plus';

// 根据环境确定API地址
const API_BASE_URL = import.meta.env.MODE === 'development' 
  ? 'http://117.72.45.141:8091' // 开发环境直接指向后端服务器
  : ''; // 生产环境使用相对路径，通过Nginx代理访问后端

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.error('API调用错误:', error);
    if (error.response) {
      const { status, data } = error.response;
      if (status === 401) {
        ElMessage.error('登录已过期，请重新登录');
        localStorage.removeItem('token');
        // 可以在这里跳转到登录页面
      } else if (status === 403) {
        ElMessage.error('没有权限访问该资源');
      } else if (status >= 500) {
        ElMessage.error('服务器错误，请稍后重试');
      } else {
        ElMessage.error(data.message || '请求失败');
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接');
    } else {
      ElMessage.error('网络错误，请检查网络连接');
    }
    return Promise.reject(error);
  }
);

// 产品模块API
export const productAPI = {
  // 分页查询产品列表
  getProductPage: (params) => api.post('/api/product/page', params),
  
  // 获取所有产品
  getAllProducts: () => api.get('/api/product/all'),
  
  // 根据ID获取产品详情
  getProductById: (productId) => api.get(`/api/product/${productId}`),
  
  // 添加产品
  addProduct: (data) => api.post('/api/product', data),
  
  // 更新产品
  updateProduct: (data) => api.put('/api/product', data),
  
  // 删除产品
  deleteProduct: (productId) => api.delete(`/api/product/${productId}`),
  
  // 批量删除产品
  batchDeleteProducts: (productIds) => api.delete('/api/product/batch', { data: productIds }),
  
  // 检查产品名称是否存在
  checkProductName: (productName, excludeId) => 
    api.get('/api/product/check-name', { params: { productName, excludeId } })
};

// 工艺路线模块API
export const processRouteAPI = {
  // 根据产品ID获取工艺路线
  getRouteByProductId: (productId) => api.get(`/api/process-route/product/${productId}`),
  
  // 根据ID获取工艺路线详情
  getRouteById: (routeId) => api.get(`/api/process-route/${routeId}`),
  
  // 创建工艺路线
  createRoute: (data) => api.post('/api/process-route', data),
  
  // 更新工艺路线
  updateRoute: (data) => api.put('/api/process-route', data),
  
  // 删除工艺路线
  deleteRoute: (routeId) => api.delete(`/api/process-route/${routeId}`),
  
  // 复制工艺路线
  copyRoute: (sourceRouteId, targetProductId, routeName) => 
    api.post('/api/process-route/copy', null, {
      params: { sourceRouteId, targetProductId, routeName }
    }),
  
  // 检查产品是否已有工艺路线
  checkProductRoute: (productId, excludeId) => 
    api.get('/api/process-route/check-product-route', { params: { productId, excludeId } })
};

// 工序模块API
export const operationAPI = {
  // 根据工艺路线ID获取工序列表
  getOperationsByRouteId: (routeId) => api.get(`/api/operation/route/${routeId}`),
  
  // 根据ID获取工序详情
  getOperationById: (operationId) => api.get(`/api/operation/${operationId}`),
  
  // 添加工序
  addOperation: (data) => api.post('/api/operation', data),
  
  // 更新工序
  updateOperation: (data) => api.put('/api/operation', data),
  
  // 删除工序
  deleteOperation: (operationId) => api.delete(`/api/operation/${operationId}`),
  
  // 批量删除工序
  batchDeleteOperations: (operationIds) => api.delete('/api/operation/batch', { data: operationIds }),
  
  // 根据机器类型ID查询工序
  getOperationsByMachineTypeId: (machineTypeId) => api.get(`/api/operation/machine-type/${machineTypeId}`),
  
  // 检查工序编号是否存在
  checkOperationCode: (routeId, operationCode, excludeId) => 
    api.get('/api/operation/check-code', { params: { routeId, operationCode, excludeId } }),
  
  // 检查工序序号是否存在
  checkSequenceNo: (routeId, sequenceNo, excludeId) => 
    api.get('/api/operation/check-sequence', { params: { routeId, sequenceNo, excludeId } })
};

// 机器类型模块API
export const machineTypeAPI = {
  // 分页查询机器类型
  getMachineTypePage: (params) => api.post('/api/machine-type/page', params),
  
  // 获取所有机器类型
  getAllMachineTypes: () => api.get('/api/machine-type/all')
};

// 原料模块API
export const materialAPI = {
  // 获取所有原料
  getAllMaterials: () => api.get('/api/material/all'),
  
  // 分页查询原料
  getMaterialPage: (params) => api.post('/api/material/page', params),
  
  // 根据ID获取原料详情
  getMaterialById: (materialId) => api.get(`/api/material/${materialId}`),
  
  // 添加原料
  addMaterial: (data) => api.post('/api/material', data),
  
  // 更新原料
  updateMaterial: (data) => api.put('/api/material', data),
  
  // 删除原料
  deleteMaterial: (materialId) => api.delete(`/api/material/${materialId}`)
};

// 库存管理模块API
export const inventoryAPI = {
  // 原料库存相关
  material: {
    // 分页查询原料库存
    getPage: (params) => api.post('/api/inventory/material/page', params),
    
    // 根据库存ID获取原料库存详情
    getById: (inventoryId) => api.get(`/api/inventory/material/${inventoryId}`),
    
    // 根据原料ID获取库存
    getByMaterialId: (materialId) => api.get(`/api/inventory/material/material/${materialId}`),
    
    // 添加原料库存
    add: (data) => api.post('/api/inventory/material', data),
    
    // 更新原料库存
    update: (data) => api.put('/api/inventory/material', data),
    
    // 删除原料库存
    delete: (inventoryId) => api.delete(`/api/inventory/material/${inventoryId}`),
    
    // 补充原料库存
    replenish: (materialId, params) => api.put(
      `/api/inventory/material/replenish/${materialId}`,
      null,
      { params }
    )
  },
  
  // 产品库存相关
  product: {
    // 分页查询产品库存
    getPage: (params) => api.post('/api/inventory/product/page', params),
    
    // 根据库存ID获取产品库存详情
    getById: (inventoryId) => api.get(`/api/inventory/product/${inventoryId}`),
    
    // 根据产品ID获取库存
    getByProductId: (productId) => api.get(`/api/inventory/product/product/${productId}`),
    
    // 添加产品库存
    add: (data) => api.post('/api/inventory/product', data),
    
    // 更新产品库存
    update: (data) => api.put('/api/inventory/product', data),
    
    // 删除产品库存
    delete: (inventoryId) => api.delete(`/api/inventory/product/${inventoryId}`)
  }
};

// 导出api实例供其他地方使用
export default api;